﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

using LuaInterface;

namespace Codeology.Auctioneer
{

    public class AuctioneerScanData : IDisposable
    {

        private bool disposed;
        private double version;
        private List<AuctioneerRealm> realms;

        private AuctioneerScanData(Stream stream)
        {
            // Mark as undisposed
            disposed = false;

            // Create LUA engine
            Lua lua = new Lua();

            try {
                // Parse LUA
                using (StreamReader reader = new StreamReader(stream)) lua.DoString(reader.ReadToEnd());

                // Get version
                version = lua.GetNumber("AucScanData.Version");

                // Create somewhere to put realms
                realms = new List<AuctioneerRealm>();

                // Get scans table
                LuaTable scans_table = (LuaTable)lua.GetTable("AucScanData.scans");

                // Process realms
                foreach(DictionaryEntry entry in scans_table) {
                    // Get realm name
                    string name = (string)entry.Key;

                    // Get realm table
                    LuaTable table = (LuaTable)entry.Value;

                    // Create realm
                    AuctioneerRealm realm = new AuctioneerRealm(name,table);

                    // Add realm to realms list
                    realms.Add(realm);
                }
            } finally {
                // Release LUA engine
                lua.Dispose();
            }
        }

        #region Static Methods

        public static AuctioneerScanData Load(Stream stream)
        {
            return new AuctioneerScanData(stream);
        }

        public static AuctioneerScanData Load(string fileName)
        {
            using (FileStream file = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.Read)) {
                return Load(file);
            }
        }

        #endregion

        #region Methods

        public void Dispose()
        {
            if (!disposed) {
                //

                // Suppress finalization
                GC.SuppressFinalize(this);

                // Mark as disposed
                disposed = true;
            }
        }

        #endregion

        #region Properties

        public double Version
        {
            get {
                return version;
            }
        }

        public AuctioneerRealm[] Realms
        {
            get {
                return realms.ToArray();
            }
        }

        #endregion

    }  

}
